﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using HIWSystem.Models;
using HIWSystem.Common;
using GalaSoft.MvvmLight.Messaging;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Windows;

namespace HIWSystem.ViewModel
{
    [MetadataType(typeof(MenuManageViewModel))]
    public class MenuManageViewModel : ViewModelBase,IDataErrorInfo
    {
        public MenuManageViewModel()
        {

            //消息标志token：ViewAlert，用于标识只阅读某个或者某些Sender发送的消息，并执行相应的处理，所以Sender那边的token要保持一致
            //执行方法Action：ShowReceiveInfo，用来执行接收到消息后的后续工作，注意这边是支持泛型能力的，所以传递参数很方便。
            Messenger.Default.Register<DataTable>(this, "NewAddMenu", LoadNewNamedMenuToComboBox);
        }
        #region 命令
        private RelayCommand newAddMenuCmd;

        public RelayCommand NewAddMenuCmd
        {
            get
            {
                if (newAddMenuCmd == null)
                {
                    newAddMenuCmd = new RelayCommand(() =>
                    {
                        ViewManager.ShowDialog("MenuNamed");
                    });
                }
                return newAddMenuCmd;
            }
            set { newAddMenuCmd = value; }
        }
        private RelayCommand loadPageCmd;

        public RelayCommand LoadPageCmd
        {
            get
            {
                if (loadPageCmd == null)
                {
                    loadPageCmd = new RelayCommand(LoadPage);
                }
                return loadPageCmd;
            }
            set { loadPageCmd = value; }
        }
        private RelayCommand unloadedPageCmd;

        public RelayCommand UnloadedPageCmd
        {
            get
            {
                if (unloadedPageCmd == null)
                {
                    unloadedPageCmd = new RelayCommand(UnloadedPage);
                }
                return unloadedPageCmd;
            }
            set { unloadedPageCmd = value; }
        }
        private RelayCommand submitCmd;

        public RelayCommand SubmitCmd
        {
            get 
            {
                if (submitCmd==null)
                {
                    submitCmd = new RelayCommand(Submit);
                }
                return submitCmd; 
            }
            set { submitCmd = value; }
        }
        private RelayCommand autoGenerateMenuLevelCmd;

        public RelayCommand AutoGenerateMenuLevelCmd
        {
            get 
            {
                if (autoGenerateMenuLevelCmd==null)
                {
                    autoGenerateMenuLevelCmd = new RelayCommand(()=> { this.MenuAccess = BusinessProcess.AutoGenerateNextMenuLevel(); });
                }
                return autoGenerateMenuLevelCmd; 
            }
            set { autoGenerateMenuLevelCmd = value; }
        }
        private RelayCommand editMenuCmd;

        public RelayCommand EditMenuCmd
        {
            get 
            {
                if (editMenuCmd==null)
                {
                    editMenuCmd = new RelayCommand(()=> {
                    //待后期开发
                    });
                }
                return editMenuCmd; 
            }
            set { editMenuCmd = value; }
        }
        private RelayCommand employeeMenuAccessManageCmd;
        /// <summary>
        /// 员工菜单权限管理
        /// </summary>
        public RelayCommand EmployeeMenuAccessManageCmd
        {
            get 
            {
                if (employeeMenuAccessManageCmd==null)
                {
                    employeeMenuAccessManageCmd = new RelayCommand(ManageEmployeeMenuAccess);
                }
                return employeeMenuAccessManageCmd; 
            }
            set { employeeMenuAccessManageCmd = value; }
        }
        #endregion
        #region 属性
        /// <summary>
        /// 表单验证错误集合
        /// </summary>
        private Dictionary<String, String> dataErrors = new Dictionary<String, String>();
        private string menuEn;
        [Required]
        public string MenuEn
        {
            get { return menuEn; }
            set { menuEn = value; this.RaisePropertyChanged(() => MenuEn); }
        }
        private int menuItemId;
        [Required]
        public int MenuItemId
        {
            get { return menuItemId; }
            set { menuItemId = value; this.RaisePropertyChanged(() => MenuItemId); }
        }


        private string menuLevel="0";
        /// <summary>
        /// 菜单等级
        /// </summary>
        [RegularExpression(@"^\d$",ErrorMessage ="菜单等级权限不正确,正确的格式是【0-9】")]
        public string MenuLevel
        {
            get { return menuLevel; }
            set { menuLevel = value; this.RaisePropertyChanged(() => MenuLevel); }
        }
        private string menuAccess;
        /// <summary>
        /// 菜单权限
        /// </summary>
        [RegularExpression(@"^[A-Z]{2}$",ErrorMessage ="菜单权限格式不正确，正确的格式是两个大写字母的组合")]
        public string MenuAccess
        {
            get { return menuAccess; }
            set { menuAccess = value; this.RaisePropertyChanged(() => MenuAccess); }
        }

        private ObservableCollection<MenuNamedEntity> newNamedMenuResource;
        /// <summary>
        /// 菜单名称集
        /// </summary>
        public ObservableCollection<MenuNamedEntity> NewNamedMenuResource
        {
            get { return newNamedMenuResource; }
            set { newNamedMenuResource = value; this.RaisePropertyChanged(() => NewNamedMenuResource); }
        }
        private ObservableCollection<MenuEntity> mainMenuResource;

        public ObservableCollection<MenuEntity> MainMenuResource
        {
            get { return mainMenuResource; }
            set { mainMenuResource = value; this.RaisePropertyChanged(() => MainMenuResource); }
        }
        private ObservableCollection<MenuEntity> menuSource;
        /// <summary>
        /// 所有菜单信息
        /// </summary>
        public ObservableCollection<MenuEntity> MenuSource
        {
            get { return menuSource; }
            set { menuSource = value; this.RaisePropertyChanged(() => MenuSource); }
        }
        private bool isEnabledEditButton;
        /// <summary>
        /// 是否启用编辑按钮
        /// </summary>
        public bool IsEnabledEditButton
        {
            get { return isEnabledEditButton; }
            set { isEnabledEditButton = value; this.RaisePropertyChanged(() => IsEnabledEditButton); }
        }

        public string Error 
        {
            get { return null; }
        }

        public string this[string columnName]
        {
            get
            {
                ValidationContext vc = new ValidationContext(this, null, null);
                vc.MemberName = columnName;
                var res = new List<ValidationResult>();
                var result = Validator.TryValidateProperty(this.GetType().GetProperty(columnName).GetValue(this, null), vc, res);
                if (res.Count > 0)
                {
                    AddDic(dataErrors, vc.MemberName);
                    return string.Join(Environment.NewLine, res.Select(r => r.ErrorMessage).ToArray());
                }
                RemoveDic(dataErrors, vc.MemberName);
                return null;
            }
        }
        #endregion
        #region 方法
        private void LoadNewNamedMenuToComboBox(DataTable dtResource)
        {
            DataTable dtMenuName = new DataTable();

            NewNamedMenuResource = new ObservableCollection<MenuNamedEntity>();
            //从菜单命名页面(MenuNamed)传递过来的值
            if (dtResource != null)
            {
                //dtMenuName = dtResource;
                dtMenuName = dtResource.Copy();
                //for (int i = 0; i < dtMenuName.Rows.Count; i++)
                //{
                //    NewNamedMenuResource.Add(new MenuNamedEntity { MenuCn = dtMenuName.Rows[i]["MenuCn"].ToString(), MenuEn = dtMenuName.Rows[i]["MenuEn"].ToString(), Id = Convert.ToInt32(dtMenuName.Rows[i]["MenuItemId"].ToString()) });
                //}
            }
            //页面加载首次添加或者添加成功以后刷新
            else
            {
                dtMenuName = BusinessProcess.GetNoConfigMenuTable();
            }
            for (int i = 0; i < dtMenuName.Rows.Count; i++)
            {
                NewNamedMenuResource.Add(new MenuNamedEntity { MenuCn = dtMenuName.Rows[i]["MenuCn"].ToString(), MenuEn = dtMenuName.Rows[i]["MenuEn"].ToString(), Id = Convert.ToInt32(dtMenuName.Rows[i]["Id"].ToString()) });
            }




        }
        private void LoadMainMenuToComboBox()
        {
            DataTable dtMenuName = new DataTable();
            //页面加载首次添加或者添加成功后刷新列表
            dtMenuName = BusinessProcess.GetConfigMenuTable();
            MainMenuResource = new ObservableCollection<MenuEntity>();
            for (int i = 0; i < dtMenuName.Rows.Count; i++)
            {
                int repeatCount = NewNamedMenuResource.Count(x => x.MenuEn == dtMenuName.Rows[i]["MenuEn"].ToString());
                if (repeatCount==0)
                    MainMenuResource.Add(new MenuEntity { MenuCn = dtMenuName.Rows[i]["MenuCn"].ToString(), MenuEn = dtMenuName.Rows[i]["MenuEn"].ToString(), Id = Convert.ToInt32(dtMenuName.Rows[i]["MenuItemId"].ToString()) });

            }
            MainMenuResource.Insert(0, new MenuEntity { Id = 0, MenuEn = "Top", MenuCn = "一级菜单" });

            //var a = from M in MainMenuResource
            //        from N in NewNamedMenuResource
            //        where M.MenuEn != N.MenuEn
            //        select new MenuEntity() { Id = M.Id, MenuCn = M.MenuCn, MenuEn = M.MenuEn };
            //MainMenuResource = new ObservableCollection<MenuEntity>();
            //foreach (var item in a)
            //{
            //    MainMenuResource.Add(item);
            //}
        }
        /// <summary>
        /// 加载页面
        /// </summary>
        private void LoadPage()
        {
            //加载菜单到下拉列表框中
            this.LoadNewNamedMenuToComboBox(null);
            //加载主菜单到下拉列表框中
            this.LoadMainMenuToComboBox();
        }
        /// <summary>
        /// 卸载页面
        /// </summary>
        private void UnloadedPage()
        {
            //卸载当前(this)对象注册的所有MVVMLight消息
            Messenger.Default.Unregister(this);
        }
        private void Submit()
        {
            if (dataErrors.Count == 0)
            {
                string retMsg = string.Empty;
                DataTable dtMenu = new DataTable();
                MenuEntity menuEntity = new MenuEntity() 
                {
                 MenuEn=this.MenuEn??"",
                 OwnerId=this.MenuItemId,
                 MenuLevel=Convert.ToInt32(this.MenuLevel),
                 MenuAccess=this.MenuAccess
                };
                retMsg = BusinessProcess.ConfigClientMenu(menuEntity, out dtMenu);
                if (retMsg.Split('|')[0] == "OK")
                {
                    MenuSource = new ObservableCollection<MenuEntity>();
                    for (int i = 0; i < dtMenu.Rows.Count; i++)
                    {
                        MenuSource.Add(
                            new MenuEntity
                            {
                                Id =Convert.ToInt32(dtMenu.Rows[i]["MenuItemId"].ToString()),
                                MenuEn= dtMenu.Rows[i]["MenuEn"].ToString(),
                                MenuCn= dtMenu.Rows[i]["MenuCn"].ToString(),
                                OwnerId= Convert.ToInt32(dtMenu.Rows[i]["OwnerId"].ToString()),
                                MenuLevel=Convert.ToInt32(dtMenu.Rows[i]["MenuItemLevel"].ToString()),
                                MenuAccess= dtMenu.Rows[i]["ActorLevel"].ToString()
                            });
                    }
                    LoadNewNamedMenuToComboBox(null);
                    LoadMainMenuToComboBox();
                    this.MenuLevel = "1";
                    this.MenuAccess = "";
                    MessageBox.Show(retMsg.Split('|')[1].ToString(), "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else
                {
                    MessageBox.Show(retMsg.Split('|')[1].ToString(), "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            } /*MessageBox.Show("验证通过！");*/
            else
                MessageBox.Show("信息输入有误！", "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Error);
        }
        /// <summary>
        /// 管理员工菜单权限
        /// </summary>
        private void ManageEmployeeMenuAccess()
        {
            Messenger.Default.Send<string>("员工菜单管理", "ShowTabItem");
        }

        #endregion
        #region 附属方法

        /// <summary>
        /// 移除字典
        /// </summary>
        /// <param name="dics"></param>
        /// <param name="dicKey"></param>
        private void RemoveDic(Dictionary<String, String> dics, String dicKey)
        {
            dics.Remove(dicKey);
        }

        /// <summary>
        /// 添加字典
        /// </summary>
        /// <param name="dics"></param>
        /// <param name="dicKey"></param>
        private void AddDic(Dictionary<String, String> dics, String dicKey)
        {
            if (!dics.ContainsKey(dicKey)) dics.Add(dicKey, "");
        }

        #endregion
    }
}

